import $ from 'zepto'
import * as _ from 'lodash'
function reachBottomLoad(options){
    document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    let distance = options.distance || 80;
    function scrollTop() {
        return Math.max(document.body.scrollTop, document.documentElement.scrollTop);
        }
      function documentHeight() {
          return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
      }
      function windowHeight(){
          return (document.compatMode == "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight;
      }
      $(window).off('scroll').on('scroll', _.throttle(function() {
          if((scrollTop() + windowHeight() >= documentHeight()-distance) && scrollTop()>0){
              if(options.callback){
                options.callback();
              }
          }
      },150));
}
function swipeHorizontal(options){
    let el = document.querySelector(options.selector);
    el.ontouchstart = (ev)=>{
        if(ev.target.className=='swiper-img'){
            return;
        }
        let touch = ev.touches[0];
        let startX = touch.pageX;
        let startY = touch.pageY;
        document.ontouchend = (event) => {
            document.ontouchmove = null;
            document.ontouchend = null;
            let swix = event.changedTouches[0].pageX - startX;
            let swiy = event.changedTouches[0].pageY - startY;
            let Bi = Math.abs(swix/swiy);
            if (swix > 70 && Bi>=3 && swiy<15) {//右滑
                options.rightCallback();
            } else if(swix < -70 && Bi>=3 && swiy<15) {//左滑
                options.leftCallback();
            } else{
                return;
            }
            options.complete();
        }
    }
}
function elementPosition(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
     curleft = obj.offsetLeft;
     curtop = obj.offsetTop;
     while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
     }
    }
    return { x: curleft, y: curtop };
  }
  
function ScrollToControl(elem,fix=0){
   var scrollPos = elementPosition(elem).y;
   scrollPos = scrollPos - document.documentElement.scrollTop-fix;
   window.scrollBy(0,scrollPos);
}
  
const Interactive = {
    reachBottomLoad: reachBottomLoad,
    swipeHorizontal: swipeHorizontal,
    ScrollToControl: ScrollToControl
}
export default Interactive